'use strict';

const Service = require('egg').Service;

class GService extends Service {
  constructor(ctx) {
    super(ctx);
    this.name = 'role';
  }

  async create(params) {
    const { mysql } = this.app;
    try {
      const { name, identity, description, active } = params;
      const createTime = new Date();
      const result = await mysql.query("INSERT INTO sys_role(id,  name,  identity,  description,  active, created_at) VALUES (REPLACE(UUID(),'-',''), ?, ?, ?, ?, ?);", [ name, identity, description, active, createTime ]);
      if (result.affectedRows === 1) {
        return result.insertId;
      }
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }

  async find(params) {
    const { mysql } = this.app;
    const { helper: { pagination } } = this.ctx;
    try {
      const { name, identity, description, active, page, size } = params;
      const pagger = pagination(page, size);
      const filters = {
        name: {
          '=': name,
        },
        identity: {
          '=': identity,
        },
        description: {
          '=': description,
        },
        active: {
          '=': active,
        },
      };
      const segments = [];
      const values = [];
      Object.keys(filters).forEach(key => {
        const item = filters[key];
        const k = Object.keys(item)[0];
        if (item[k]) {
          segments.push(`(${key} ${k} ? )`);
          values.push(item[k]);
        }
      });
      const select = 'SELECT * FROM `sys_role`';
      const wheres = segments.length ? `WHERE ${segments.join(' OR ')}` : '';
      const order = 'ORDER BY `created_at` ASC';
      const limit = 'LIMIT ? OFFSET ?';
      const count = await mysql.query('SELECT COUNT(*) as total FROM `sys_role`' + wheres, [ ...values ]);
      const result = await mysql.query([ select, wheres, order, limit ].join(' '), [ ...values, pagger.limit, pagger.offset ]);
      return {
        pagination: {
          total: count[0].total,
          page: pagger.page,
          size: pagger.size,
        },
        list: result,
      };
    } catch (error) {
      this.ctx.throw(500);
    }
  }

  async findOne(params) {
    const { mysql } = this.app;
    try {
      const { id } = params;
      const result = await mysql.get('sys_role', { id });
      return result;
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }

  async update(params) {
    const { mysql } = this.app;
    try {
      const { id, name, identity, description, active } = params;
      const updateTime = new Date();
      const result = await mysql.query('UPDATE `sys_role` SET `name`=?, `identity`=?, `description`=?, `active`=?, `updated_at`=? WHERE `id`=?', [ name, identity, description, active, updateTime, id ]);
      if (result.affectedRows === 1) {
        return {};
      }
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }

  async destroy(params) {
    const { mysql } = this.app;
    try {
      const { id } = params;
      const result = await mysql.delete('cms_category', { category_id: id });
      if (result.affectedRows === 1) {
        return {};
      }
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }
}

module.exports = GService;
